package com.hontech.kaltaapp.ui.parts

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.FrameLayout
import androidx.recyclerview.widget.RecyclerView
import com.google.android.flexbox.FlexDirection
import com.google.android.flexbox.FlexWrap
import com.google.android.flexbox.FlexboxLayoutManager
import com.hontech.kaltaapp.R
import com.hontech.kaltaapp.device.event.DeviceStatus
import com.hontech.kaltaapp.device.ota
import com.hontech.kaltaapp.ui.dialog.runProg
import com.hontech.kaltaapp.ui.view.LabelTextView
import com.hontech.kaltaapp.utils.AppTask
import com.hontech.kaltaapp.utils.Http
import com.hontech.kaltaapp.utils.Version
import com.hontech.kaltaapp.utils.installApk2
import com.hontech.kaltaapp.utils.onClick
import com.hontech.kaltaapp.utils.register
import com.hontech.kaltaapp.utils.unregister
import kotlinx.coroutines.delay
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

private const val TYPE_MCU = 0
private const val TYPE_APP = 1
class OTAParts(context: Context, attrs: AttributeSet) : FrameLayout(context, attrs) {

    private val rv: RecyclerView
    private val ltMcu: LabelTextView
    private val ltApp: LabelTextView

    init {
        val view = LayoutInflater.from(context).inflate(R.layout.parts_ota, this)
        val mcu = view.findViewById<Button>(R.id.id_ota_btn_query_mcu)
        val app = view.findViewById<Button>(R.id.id_ota_btn_query_app)
        ltMcu = view.findViewById(R.id.id_ota_lt_mcu_version)
        ltApp = view.findViewById(R.id.id_ota_lt_app_version)
        rv = view.findViewById(R.id.id_ota_rv)
        mcu.onClick { onClickQueryMcu() }
        app.onClick { onClickQueryApp() }

        val m = FlexboxLayoutManager(context, FlexDirection.ROW, FlexWrap.WRAP)
        rv.layoutManager = m

        AppTask.post {
            ltApp.set(Version)
        }
    }

    private suspend fun onClickQueryMcu() {
        runProg("MCU版本", "查询") {
            val result = Http.queryMcu()
            rv.adapter = Adapter(TYPE_MCU, result)
        }
    }

    private suspend fun onClickQueryApp() {
        runProg("APP版本", "查询") {
            val result = Http.queryApkFile()
            rv.adapter = Adapter(TYPE_APP, result)
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
    fun onStatusUpdate(status: DeviceStatus) {
        ltMcu.set(status.appVersion)
    }

    override fun onWindowVisibilityChanged(visibility: Int) {
        super.onWindowVisibilityChanged(visibility)
        if (visibility == VISIBLE) {
            register(this)
        } else {
            unregister(this)
        }
    }

}

private fun sizeStr(size: Int): String {
    return if (size < 1024) {
        "${size}Byte"
    } else if (size < (1024 * 1024)) {
        "${size/1024}KB"
    } else if (size < (1024 * 1024 * 1024)) {
        "${size/1024/1024}MB"
    } else {
        "${size/1024/1024/1024}GB"
    }
}

private class Item(view: View) : RecyclerView.ViewHolder(view) {

    private val ltVersion = view.findViewById<LabelTextView>(R.id.id_item_ota_lt_version)
    private val ltDate = view.findViewById<LabelTextView>(R.id.id_item_ota_lt_date)
    private val ltSize = view.findViewById<LabelTextView>(R.id.id_item_ota_lt_size)
    private val ltDescribe = view.findViewById<LabelTextView>(R.id.id_item_ota_lt_describe)
    private val btnUpdate = view.findViewById<Button>(R.id.id_item_btn_update)

    private suspend fun updateMCU(id: Int) {
        runProg("MCU更新", "更新") { dialog ->
            val buf = Http.doDownloadBin(id)
            dialog.setMsg("下载成功开始更新")
            ota(buf) {
                dialog.setMsg("进度:${it}%")
            }
        }
    }

    private suspend fun updateApp(id: Int) {
        runProg("APP更新", "更新") {dialog ->
            val path = Http.doDownloadApk(id) {
                dialog.setMsg("下载进度:${it}%")
            }
            delay(100)
            dialog.setMsg("更新成功 开始安装")
            installApk2(path)
        }
    }


    fun setUp(file: Http.StoreFile, type: Int) {
        ltVersion.set(file.version)
        ltDate.set(file.time())
        ltSize.set(sizeStr(file.size))
        ltDescribe.set(file.description)
        btnUpdate.onClick {
            if (type == TYPE_MCU) {
                updateMCU(file.id)
            } else {
                updateApp(file.id)
            }
        }
    }
}

private class Adapter(val type: Int, val result: Array<Http.StoreFile>) : RecyclerView.Adapter<Item>() {

    override fun getItemCount(): Int {
        return result.size
    }

    override fun onBindViewHolder(holder: Item, position: Int) {
        val file = result[position]
        holder.setUp(file, type)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Item {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_ota_info, parent, false)
        return Item(view)
    }
}



